/**
 * @author 陈泰来
 * @version V1.0
 * @Project echo-java-base
 * @Title 弹跳框
 * @Description *
 * @Package concurrent.runningball
 * @date 2021/4/1 3:54 下午
 * @Copyright:学如逆水行舟，不进则退 .
 */
package concurrent.runningball;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;

public class BounceFrame extends JFrame {


    private BallComponent comp;
    public static final int DEFAULT_WIDTH = 450;
    public static final int DEFAULT_HEIGHT = 350;
    public static final int STEPS = 3000;
    public static final int DELAY = 3;

    public BounceFrame() throws HeadlessException {
        setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
        setTitle("小球弹跳窗口");

        comp = new BallComponent();
        add(comp, BorderLayout.CENTER);

        JPanel buttonPanel = new JPanel();
        addButton(buttonPanel, "开始", e -> {
            addBall();
        });

        addButton(buttonPanel, "关闭", e -> {
            System.exit(0);
        });

        add(buttonPanel, BorderLayout.SOUTH);
    }

    /**
     * @return void
     * @author chentl
     * @description 添加按钮
     * @date 2021/4/1 4:07 下午
     * @params [c, title, listener]
     */
    public void addButton(Container c, String title, ActionListener listener) {
        JButton button = new JButton(title);
        c.add(button);
        button.addActionListener(listener);
    }

    public void addBall() {
        try {
            Ball ball = new Ball();
            comp.add(ball);

            for (int i = 1; i < STEPS; i++) {
                ball.move(comp.getBounds());
                comp.paint(comp.getGraphics());

                Thread.sleep(DELAY);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
